<script>
import { greeting } from '@/utils/greeting'
import { mapGetters } from 'vuex'
import { list, updateStartPic, updateEndPic, getPaperDetail, apiWorkFile, apiStudentWorkSubmit } from '@/api/experiment'
import GroupAdd from './components/GroupAdd'
import { getToken } from '@/utils/auth'
import QRCode from "qrcode"
import GeWuTest from './components/GeWuTest/index.vue'

export default {
  components: {
    GroupAdd,
    GeWuTest
  },
  data() {
    return {
      hello: '',
      statistic: {
        normal: 0,
        done: 0
      },
      query: {
        experimentName: '',
        pageNum: 1,
        pageSize: 10
      },
      tableList: [],
      total: 0,
      uploadImgUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      student: {
        visible: false,
        guideId: '',
        workId: ''
      },
      uploadVisible: false,
      qrUrl: '',
      previewVisible: false,
      previewList: []
    }
  },
  mounted() {
    this.hello = greeting()
    this.initData()
  },
  computed: {
    ...mapGetters(['avatar', 'nickName'])
  },
  methods: {
    initData() {
      list(this.query.pageNum, this.query.pageSize, this.query.experimentName).then(res => {
        this.tableList = []
        res.data['records'].forEach(item => {
          this.tableList.push({
            ...item,
            fileList1: [],
            fileList2: []
          })
        })
        this.total = res.data['total']
      })
    },
    handleQuery() {
      this.query.pageNum = 1
      this.initData()
    },
    handleReset() {
      this.query.experimentName = ''
      this.initData()
    },
    handleSizeChange(e) {
      this.query.pageNum = 1
      this.query.pageSize = e
      this.initData()
    },
    handleCurrentChange(e) {
      this.query.pageNum = e
      this.initData()
    },
    handleBookView(row) {
      // guidebookId
      // getPaperDetail(row['guidebookId']).then(res => {
      //   console.log(res)
      //   sessionStorage.setItem('documentHtml', JSON.stringify(res.data))
      //   this.student.visible = true
      // })
      this.$confirm(this.$locale('experiment.components.list.The guidebook is about to be completed and cannot be exited. Do you want to continue'), this.$locale('formMarkering.list.tip2'), {
        confirmButtonText: this.$locale('formMarkering.list.tip3'),
        cancelButtonText: this.$locale('formMarkering.list.tip4'),
        type: 'warning'
      }).then(() => {
        this.student.guideId = row['guidebookId']
        this.student.workId = row['id']
        this.student.visible = true
      })
    },
    handleSubmit(row) {
      apiStudentWorkSubmit(row['id']).then(res => {
        if (res.data) {
          this.initData()
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    handleViewBeforePic(row) {

    },
    handleViewAfterPic(row) {

    },
    handleAddGroupItem(row) {
      this.$refs.refGroupAdd.$show(row)
    },
    handleUpload1(row, e) {
      const data = {
        experimentPicture: e['url'],
        id: row['id']
      }
      updateStartPic(data).then(() => {
        this.$message.success(this.$locale('formMarkering.list.tip5'))
        this.initData()
      })
    },
    handleUpload2(row, e) {
      const data = {
        experimentPicture: e['url'],
        id: row['id']
      }
      updateEndPic(data).then(() => {
        this.$message.success(this.$locale('formMarkering.list.tip5'))
        this.initData()
      })
    },
    handleUploadPic(isBefore = false, isAfter = false, workId = null) {
      const token = getToken()
      const id = workId || this.student.workId
      let url = ''
      if (isBefore) {
        url = `http://180.76.188.13:10010?workId=${id}&token=${token}&isBefore=true`
      } else if (isAfter) {
        url = `http://180.76.188.13:10010?workId=${id}&token=${token}&isAfter=true`
      } else {
        url = `http://180.76.188.13:10010?workId=${id}&token=${token}`
      }
      console.log(url)
      this.uploadVisible = true
      const canvas = this.$refs.refQrcodeCanvas
      setTimeout(() => {
        // QRCode.toCanvas(canvas, url, { width: 430 }, (error, codeUrl) => {
        //   if (error) console.error("生成二维码失败:", error);
        //   else console.log("二维码已生成");
        //   console.log(codeUrl)
        // });
        QRCode.toDataURL(url, (err, codeUrl) => {
          this.qrUrl = codeUrl
        })
      }, 400)
    },
    handlePreviewPic(row) {
      apiWorkFile(row['id']).then(res => {
        this.previewList = []
        if (res.data['workFiles'].length > 0) {
          this.previewList = [...res.data['workFiles']]
          this.previewVisible = true
        } else {
          this.$message.warning(this.$locale('experiment.components.list.There are currently no photos available, please add them!'))
        }
      })
    },
    handleSubmitExperiment() {
      this.$confirm(this.$locale('experiment.components.list.The guidebook is about to be submitted. Do you want to continue?'), this.$locale('experiment.components.list.ask about'), {
        confirmButtonText: this.$locale('formMarkering.list.tip3'),
        cancelButtonText: this.$locale('formMarkering.list.tip4'),
        type: 'warning'
      }).then(() => {
        this.$refs.refGeWuTest.$submit().then(() => {
          this.student.visible = false
          this.initData()
        })
      })
    }
  }
}
</script>

<template>
  <div class='experiment-list-container'>
    <div class='experiment-header'>
      <div class='experiment-header-left'>
        <div class='experiment-header-avatar' :style='{ backgroundImage: `url(${avatar})` }' />
        <div class='experiment-header-hello'>
          <h3 style='margin: 0;'>{{ hello }}，{{ nickName }}同学，祝你开心每一天！</h3>
          <div style='display: flex; align-items: center; color: rgba(0, 0, 0, 0.42);'>
            <span>{{ $locale('student.student') }}</span>
            <el-divider direction="vertical" />
            <span>{{ $locale('experiment.components.list.Beijing Institute of Technology - Class 2, Grade 99') }}</span>
          </div>
        </div>
      </div>
      <div class='experiment-header-right'>
        <el-row :gutter='12'>
          <el-col :span='12'>
            <el-statistic :title="$locale('experiment.components.list.To be completed experiment')" :value='statistic.normal' :value-style='{ fontSize: `16px` }' />
          </el-col>
          <el-col :span='12'>
            <el-statistic :title="$locale('experiment.components.list.Experiment completed')" :value='statistic.done' :value-style='{ fontSize: `16px` }' />
          </el-col>
        </el-row>
      </div>
    </div>
    <el-divider />
    <div class='query-form-container'>
      <el-form label-position='top' inline>
        <el-form-item :label="$locale('geWudevice.add.Experiment Name')">
          <el-input v-model='query.experimentName' :placeholder="$locale('geWuExperiment.Please enter the experiment name')" clearable />
        </el-form-item>
      </el-form>
      <div style='display: flex; align-items: center;'>
        <el-button type='primary' @click='handleQuery'>{{ $locale('experiment.components.list.query') }}</el-button>
        <el-button @click='handleReset'>{{ $locale('geWudevice.reset') }}</el-button>
      </div>
    </div>
    <div class='table-container'>
      <el-table :data='tableList' style='width: 100%;' stripe>
        <el-table-column prop='experimentName' :label="$locale('geWudevice.add.Experiment Name')" width='224px' />
        <el-table-column prop='teacherName' :label="$locale('student.add.experiment.teacher')" />
        <el-table-column :label="$locale('geWuExperiment.classification')">
          <template slot-scope='scope'>
            <span v-if="scope.row['experimentType'] === 1">{{ $locale('experiment.components.list.Electrical and Electronic Engineering') }}</span>
            <span v-if="scope.row['experimentType'] === 2">{{ $locale('experiment.components.list.Power electronics') }}</span>
            <span v-if="scope.row['experimentType'] === 3">{{ $locale('experiment.components.list.Motor principle') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$locale('geWuExperiment.Experimental time')">
          <template slot-scope='scope'>
            <span>{{ scope.row['experimentTime'] }}{{ $locale('geWudevice.add.minute') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$locale('geWuExperiment.difficulty')">
          <template slot-scope='scope'>
            <span>{{ scope.row['difficultyLevel'] }}星</span>
          </template>
        </el-table-column>
        <el-table-column prop='startWorkTime' :label="$locale('student.add.experiment.Operation time')" width='155px' />
        <el-table-column :label="$locale('jobList.job status')">
          <template slot-scope='scope'>
            <span v-if="scope.row['workStatus'] === 0">{{ $locale('jobList.not submitted') }}</span>
            <span v-if="scope.row['workStatus'] === 1">{{ $locale('jobList.submitted') }}</span>
            <span v-if="scope.row['workStatus'] === 2">{{ $locale('jobList.Uncorrected') }}</span>
            <span v-if="scope.row['workStatus'] === 3">{{ $locale('jobList.Corrected') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop='submitDate' :label="$locale('jobList.Submission time')" width='155px' />
        <el-table-column prop='' :label="$locale('jobList.Team members')" show-overflow-tooltip width='200px'>
          <template slot-scope='scope'>
            <span>{{ scope.row['teamNames'] }}</span>
            <el-divider direction="vertical" />
            <el-button type="primary" icon="el-icon-plus" size='mini' plain circle @click='handleAddGroupItem(scope.row)' />
          </template>
        </el-table-column>
        <el-table-column :label="$locale('jobList.Take photos before the experiment')" width='95px'>
          <template slot-scope='scope'>
<!--            <el-upload v-if="!scope.row['startExperimentPicture']" multiple :limit='1' :action='uploadImgUrl' :headers="headers" :file-list="scope.row['fileList1']" :on-success="e => handleUpload1(scope.row, e)">-->
<!--              <el-button type='text'>{{ $locale('experiment.components.list.Upload photos') }}</el-button>-->
<!--            </el-upload>-->
            <el-link v-if="!scope.row['startExperimentPicture']" type="primary" @click="handleUploadPic(true, false, scope.row['id'])">{{ $locale('experiment.components.list.Upload photos') }}</el-link>
            <el-image v-if="scope.row['startExperimentPicture']" style="width: 48px; height: 48px;" :src="scope.row['startExperimentPicture']" :preview-src-list="[scope.row['startExperimentPicture']]" />
          </template>
        </el-table-column>
        <el-table-column :label="$locale('experiment.components.list.Inventory results')">
          <template slot-scope='scope'>
            <span v-if="scope.row['startExperimentInventory']">{{ $locale('classList.normal') }}</span>
            <span v-if="!scope.row['startExperimentInventory']">{{ $locale('experiment.components.list.abnormal') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop='startExperimentWarnHandle' :label="$locale('experiment.components.list.Warning handling')" width='155px' />
        <el-table-column :label="$locale('jobList.Take photos after the experiment')" width='95px'>
          <template slot-scope='scope'>
<!--            <el-upload v-if="!scope.row['endExperimentPicture']" multiple :limit='1' :action='uploadImgUrl' :headers="headers" :file-list="scope.row['fileList1']" :on-success="e => handleUpload2(scope.row, e)">-->
<!--              <el-button type='text'>{{ $locale('experiment.components.list.Upload photos') }}</el-button>-->
<!--            </el-upload>-->
            <el-link v-if="!scope.row['endExperimentPicture']" type="primary" @click="handleUploadPic(false, true, scope.row['id'])">{{ $locale('experiment.components.list.Upload photos') }}</el-link>
            <el-image v-if="scope.row['endExperimentPicture']" style="width: 48px; height: 48px;" :src="scope.row['endExperimentPicture']" :preview-src-list="[scope.row['startExperimentPicture']]" />
          </template>
        </el-table-column>
        <el-table-column :label="$locale('experiment.components.list.Inventory results')">
          <template slot-scope='scope'>
            <span v-if="scope.row['endExperimentInventory']">{{ $locale('classList.normal') }}</span>
            <span v-if="!scope.row['endExperimentInventory']">{{ $locale('experiment.components.list.abnormal') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop='endExperimentWarnHandle' :label="$locale('experiment.components.list.Warning handling')" width='155px' />
        <el-table-column prop='experimentFraction' :label="$locale('experiment.components.list.Experimental score')" />
        <el-table-column fixed="right" :label="$locale('formMarkering.list.Guidebook')">
          <template slot-scope='scope'>
            <el-button v-if="scope.row['workStatus'] === 0" type="text" @click='handleBookView(scope.row)'>{{ $locale('formMarkering.list.Guidebook') }}</el-button>
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$locale('formMarkering.list.operate')" width="120px">
          <template slot-scope='scope'>
            <el-button v-if="scope.row['workStatus'] === 0" type="text" @click='handleSubmit(scope.row)'>{{ $locale('myExperiment.studentListDialog.submit') }}</el-button>
<!--            <el-button type="text" @click="handleUploadPic(scope.row)">上传照片</el-button>-->
            <el-button type="text" @click="handlePreviewPic(scope.row)">{{ $locale('experiment.components.list.View photos') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class='page-container'>
      <el-pagination :current-page="query.pageNum"
                     :page-sizes="[10, 50, 100, 200, 500]"
                     :page-size="query.pageSize"
                     :total='total'
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change='handleSizeChange'
                     @current-change='handleCurrentChange' />
    </div>
    <group-add ref='refGroupAdd' @refresh='initData' />

    <el-dialog :visible.sync='student.visible' :title="$locale('formMarkering.list.Guidebook')" :show-close="false" destroy-on-close fullscreen>
      <ge-wu-test ref="refGeWuTest" :test-id="student.guideId" />
      <template #footer>
        <el-button type="primary" @click="handleUploadPic()">{{ $locale('experiment.components.list.Upload photos') }}</el-button>
        <el-button type="primary" @click="handleSubmitExperiment">{{ $locale('experiment.components.list.complete') }}</el-button>
      </template>
    </el-dialog>
    <el-dialog :visible.sync="uploadVisible" :title="$locale('experiment.components.list.Scan the code to upload experimental images')" width="380px">
<!--      <canvas ref="refQrcodeCanvas" width="430" height="430" style></canvas>-->
      <img :src="qrUrl" alt="" style="width: 360px; height: 360px;">
    </el-dialog>
    <el-dialog :visible.sync="previewVisible" :title="$locale('experiment.components.list.Preview experimental images')" width="640px" destroy-on-close>
      <div class="preview-img-bound">
        <el-image v-for="(img, index) in previewList" :key="index" :preview-src-list="[img['fileUrl']]" class="preview-img" :src="img['fileUrl']" alt="" />
      </div>
    </el-dialog>
  </div>
</template>

<style lang='scss'>
.preview-img-bound {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  height: fit-content;

  .preview-img {
    width: calc((100% - 24px) / 3);
    height: auto;
    margin-right: 12px;
    margin-bottom: 12px;

    &:nth-child(3n) {
      margin-right: 0;
    }
  }
}

.experiment-list-container {
  height: 100%;
  padding: 15px;

  .experiment-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .experiment-header-left {
      display: flex;
      align-items: center;

      .experiment-header-avatar {
        width: 64px;
        height: 64px;
        border: 2px solid #d9d9d9;
        border-radius: 50%;
        background-color: #fff;
        background-size: 100% 100%;
      }

      .experiment-header-hello {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        flex-direction: column;
        height: 56px;
        margin-left: 12px;
      }
    }

    .experiment-header-right {

      .el-statistic {

        .head {

          .title {
            font-size: 18px;
          }
        }
      }
    }
  }

  .query-form-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .page-container {
    margin-top: 12px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  .el-dialog__body {
    padding: 10px;
  }
}

.el-dialog__body {
  height: calc(100% - 120px);
}
</style>
